<?

global $db, $EXCMS;

if ($EXCMS != "work") {
	header ("Location: ../../index.php");
	exit;
}

die ('Это отключенный блок fast_write');

//error_reporting (E_ALL);

if (is_admin()) do_action ();

function do_action () {
	global $db, $GLOBAL_USER;
	
	
	if (isset($_POST['title'])) {
		$title = $_POST['title'];
		$category = $_POST['category'];
		$text = stripslashes ($_POST['big_text']);
		$tags = $_POST['tags'];
		(isset($_POST['auto_tag'])) ? $auto_tag = "yes" : $auto_tag = "no";
		
		if ($title != "" && $text != "" && $category != "") {
			if ($db->query ("INSERT INTO expl_articles VALUES (0, '$category', '$title', '$text', '{$GLOBAL_USER['user_id']}', '".time()."', 'on', '', '', 'yes', 'no', 'on', '$tags', '0', '0', '$auto_tag')")) site_message ("Статья добавлена!");
			else site_error (mysql_error());
		}
		else site_error ("Не заполнены необходимые поля!");	
	}
	
	print "\n<p><a href=\"/\" onclick=\"show_block(); return false;\">Написать что-нибудь</a></p>";	
	build_form ($_POST['title'], $_POST['category'], $_POST['big_text'], $_POST['tags']);
	
print <<<HTML

<script type="text/javascript">
function show_block () {
	 if (document.getElementById("fast_write").style.display == "none") document.getElementById("fast_write").style.display = "";
	 else document.getElementById("fast_write").style.display = "none";
}
</script>

HTML;
	if (isset($_POST['title'])) print "\n<script type=\"text/javascript\">show_block();</script>";
	
}

function build_form ($title, $cat, $text, $tags) {
	
	$cats = build_cats ($cat);
	
$return = <<<FORM

<style type="text/css">
<!--
a img{
  border: 0;
}
.panel{
  background: #F0F0F0;
  height: 24px;
  width: 80%;
  padding: 1px;
}
.panel a.buttn{
  display: block;
  width:20px;
  height: 20px;
  padding: 1px;
  float: left;
  border: solid #F0F0F0 1px;
  background: #F0F0F0;
}
.panel a.buttn:hover{
  border: solid #cccccc 1px;
}
.areadiv{
}
.htmlarea{
  border: 1px solid #CCCCCC;
  background: #FFFFFF;
  color: #000000;
  width: 100%;
  height: 100px;
}
.addimgdiv{
  width: 100%;
  border: dashed #cccccc 1px;
  padding: 10px;
  padding-top: 0px;
  display: none;
}
.addimgdiv form
{
  padding: 0px;
  margin: 0px;
}
.addimgdiv label{
  margin-top: 5px;
  display: block;
}
.addimgdiv .buttns{
  padding-top: 10px;
}
div#picuploadform{
  position: absolute;
  width: 34%;
  left: 33%;
  top: 250px;
  background: #FFFFFF;
  border: #EBEBEB 5px solid;
  display: none;
  z-index: 99;
}
div#picuploadform table {
	width: 100%;
	border: silver 1px solid;
}

div#screen{
  position: absolute; top: 0; left: 0; right: 0; width: 100%; height: 100%; z-index: 98;
  display: none;
  background: url("/images/trans.png");
}
* html div#screen{
    background-color: #333;
    background-color: transparent;
    background-image: url("/images/spacer.gif");
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/images/trans.png", sizingMethod="scale");
}
-->
</style>

<script type="text/javascript">
<!--
var mouseY;
var textarea_height;
var undo='';
var quote=false;

//undo
function text_undo(){
  if (undo) document.getElementById("htmlarea").value=undo;
  document.getElementById("undoimg").src="/images/editor/undo_grey.gif";
}
function text_save_undo(){
  undo=document.getElementById("htmlarea").value;
  document.getElementById("undoimg").src="/images/editor/undo.gif";
}
function text_clear_undo(){
  undo='';
  document.getElementById("undoimg").src="/images/editor/undo_grey.gif";
}
//

//cursor
function getCursor(input)
{
  var result = { start: 0, end: 0 };
  if (input.setSelectionRange)
  {
    result.start= input.selectionStart;
    result.end = input.selectionEnd;
  }
  else if (!document.selection) { return 0; }
  else if (document.selection && document.selection.createRange)
  {

    var range = document.selection.createRange();
    var stored_range = range.duplicate();
    stored_range.moveToElementText(input);
    stored_range.setEndPoint('EndToEnd', range);
    result.start = stored_range.text.length - range.text.length;
    result.end = result.start + range.text.length; //}


  }
  return result;
}
function setCursor(txtarea, start, end){

  if(txtarea.createTextRange) {
        var range = txtarea.createTextRange();
        range.move("character", start);
        range.select();
    } else if(txtarea.selectionStart) {
        txtarea.setSelectionRange(start, end);
    }

}

function insert_tag(starttag,endtag){
text_save_undo();

var txtarea = document.getElementById("htmlarea");
txtarea.focus();
var scrtop = txtarea.scrollTop;
var cursorPos=getCursor(txtarea); 

if (cursorPos.start==cursorPos.end)
{
var nuCursorPos=cursorPos.start+starttag.length;
txtarea.value = txtarea.value.substring(0,cursorPos.start)+starttag+endtag+txtarea.value.substr(cursorPos.start );
setCursor(txtarea,nuCursorPos,nuCursorPos);
}
else{
var txt_pre=txtarea.value.substring (0,cursorPos.start);
var txt_sel=txtarea.value.substring(cursorPos.start,cursorPos.end);
var txt_aft=txtarea.value.substring(cursorPos.end);
txtarea.value = txt_pre+starttag+txt_sel+endtag+txt_aft;
var nuCursorPos=String(txt_pre+starttag+txt_sel+endtag).length;
setCursor(txtarea,nuCursorPos,nuCursorPos);
}
if (scrtop) txtarea.scrollTop=scrtop;
}

function insert_text_quote(){
  var txtarea = document.getElementById("htmlarea");
  var cur = getCursor(txtarea);
  if (cur.start!=cur.end){
    insert_tag("&laquo;", "&raquo;");
  }
  else
  {
    document.getElementById("quoteimg").src=quote?"/images/editor/raquo.gif":"/images/editor/laquo.gif";
    insert_tag("", quote?"&laquo;":"&raquo;");
    quote=!quote;
  }
}
function insert_text_mdash(){
  insert_tag("", "&mdash;");
}
function insert_text_blockquote(){
  insert_tag("<blockquote>", "</blockquote>");
}
function insert_text_b(){
  insert_tag("<strong>", "</strong>");
}
function insert_text_img(){

  document.getElementById("picuploadform").style.display="block";
  document.getElementById("screen").style.display="block";
}
function insert_text_img_close(){
  document.getElementById("picuploadform").style.display="none";
  document.getElementById("screen").style.display="none";
}
function insert_text_i(){
  insert_tag("<em>", "</em>");
}
function insert_text_user(){
  var txtarea = document.getElementById("htmlarea");
  var cur = getCursor(txtarea);

  var username=window.prompt("Кто?", '');
  if (username){
    if (cur.start!=cur.end){
       insert_tag('<hh user="'+username+'">', '</hh>');
    }
    else
    {
      insert_tag('', '<hh user="'+username+'" />');
    }
  }
}
function insert_text_u(){
  insert_tag("<u>", "</u>");
}
function insert_text_s(){
  insert_tag("<s>", "</s>");
}
function insert_text_link(){
  var txtarea = document.getElementById("htmlarea");
  var cur = getCursor(txtarea);

  if (cur.start!=cur.end){
    var hreff=window.prompt("Введите URL ссылки", '');
    var regexx = new RegExp('([A-Za-z][A-Za-z0-9+.-]{1,120}:[A-Za-z0-9/](([A-Za-z0-9$_.+!*,;/?:@&~=-])|%[A-Fa-f0-9]{2}){1,333}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*,;/?:@&~=%-]{0,1000}))?)');


    if (hreff && hreff.match(regexx)) {
        insert_tag('<a href="'+hreff+'">', "</a>");
    }
    else alert("Это не URL");
  }
  else{
    alert("Сначала выделите текст, который вы желаете сделать ссылкой");
  }
}
function resize_mousemove(evt){
  if (!evt) evt=this.event;
  if (evt.pageY)
    var newheight=evt.pageY-mouseY;
  else
    var newheight=evt.clientY-mouseY;
  if (newheight>=50){
    document.getElementById("htmlarea").style.height=newheight+"px";
    textarea_height=newheight;
  }
}
function resize_start(evt){
  if (!evt) evt=this.event;
  if (!textarea_height) textarea_height=100;
  if (evt.pageY)
    mouseY=evt.pageY-textarea_height;
  else
    mouseY=evt.clientY-textarea_height;
  if (document.addEventListener){ //GECKO
    document.addEventListener('mousemove',resize_mousemove,false);
  }
  else{//IE
    document.attachEvent('onmousemove',resize_mousemove);
  }
}

function resize_stop(){
  if (document.addEventListener){ //GECKO
    document.removeEventListener('mousemove',resize_mousemove,false);
  }
  else {//IE
    document.detachEvent('onmousemove',resize_mousemove);
  }
}

if (document.addEventListener){ //GECKO
  document.addEventListener('mouseup',resize_stop,false);
}
else {//IE
  document.attachEvent('onmouseup',resize_stop);
}
//
-->
</script>

<div id="picuploadform">
<form style="width: 100%;" target="upframe" action="/api/upload_imges/" method="POST" enctype="multipart/form-data">
<table width="100%" cellspacing="0" cellpadding="5">
	<tr>
		<td width="23%">Изоображение:</td>
		<td width="77%"><input type="file" name="image" style="width: 100%;"></td>
	</tr>
	<tr>
		<td>Ширина:</td>
		<td><input type="text" name="width" value="" style="width: 100px;"><br /><span class="help">По-умолчанию и максимальное значение 400.</span></td>
	</tr>
	<tr>
		<td>Выравнивание:</td>
		<td><select name="align">
				<option value="">нет
				<option value="left">слева
				<option value="center">по центру
				<option value="right">справа
		</select></td>
	</tr>
	<tr>
		<td>Описание:</td>
		<td><input type="text" name="alt" value="" style="width:100%;"></td>
	</tr>
	<tr>
		<td colspan="2">
			<input id="pb1" type="submit" value="Загрузить">
			<input id="pb2" type="button" onClick="return insert_text_img_close();" value="Закрыть">
			<span style="display: none;"><iframe src="about:blank" width="1" height="1" name="upframe"></iframe></span>
		</td>
	</tr>
</table>
</form>
</div>

<div id="fast_write" style="display:none;">
<form action="" method="POST" name="record">
<table width="100%" cellspacing="0" cellpadding="3">
	<tr>
		<td width="10%">Title:</td>
		<td><input type="text" name="title" value="$title" style="width:50%;" /></td>
	</tr>
	<tr>
		<td>Category:</td>
		<td><select name="category">$cats</select></td>
	</tr>
	<tr>
		<td colspan="2">
		
		<div id="panel" class="panel">
			 <a href="#" onclick="insert_text_b(); return false;" class="buttn"><img src="/images/editor/bold_ru.gif" width="20" height="20" alt=" " title="жирный"></a>
			 <a href="#" onclick="insert_text_i(); return false;" class="buttn"><img src="/images/editor/italic_ru.gif" width="20" height="20" alt=" " title="курсив"></a>
			 <a href="#" onclick="insert_text_u(); return false;" class="buttn"><img src="/images/editor/underline_ru.gif" width="20" height="20" alt=" " title="подчеркнутый"></a>
			 <a href="#" onclick="insert_text_s(); return false;" class="buttn"><img src="/images/editor/strikethrough.gif" width="20" height="20" alt=" " title="зачеркнуть"></a>
			 <a href="#" onclick="insert_text_link(); return false;" class="buttn"><img src="/images/editor/link.gif" width="20" height="20" alt=" " title="вставить ссылку"></a>
			 <a href="#" onclick="insert_text_blockquote(); return false;" class="buttn"><img src="/images/editor/indent.gif" width="20" height="20" alt=" " title="отступ"></a>
			 <a href="#" onclick="insert_text_quote(); return false;" class="buttn"><img src="/images/editor/laquo.gif" width="20" height="20" alt=" " title="кавычки" id="quoteimg"></a>
			 <a href="#" onclick="insert_text_mdash(); return false;" class="buttn"><img src="/images/editor/mdash.gif" width="20" height="20" alt=" " title="тире"></a>
			 <a href="#" onclick="insert_text_img(); return false;" class="buttn"><img src="/images/editor/image.gif" width="20" height="20" alt=" " title="вставить изображение"></a>
			 <a href="#" onclick="text_undo(); return false;" class="buttn"><img src="/images/editor/undo_grey.gif" width="20" height="20" alt=" " title="отменить" id="undoimg"></a>
			</div>
		
		<textarea id="htmlarea" class="htmlarea" onkeypress="text_clear_undo()"  rows="10" name="big_text" style="width:80%;">$text</textarea>
		 <br /><div style="margin-right:20%;background: url(/images/editor/statusbar_resize.gif); width: 11px; height: 20px; float: right; cursor: nw-resize" onmousedown="resize_start(event); return false;" onmouseup="resize_stop"></div></td>
	</tr>
	<tr>
		<td>Tags:</td>
		<td><input type="text" name="tags" value="$tags" style="width:50%" /></td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="auto_tag" value="yes" id="auto_tag" /> <label for="auto_tag">Auto tag.</label></td>
	</tr>
	<tr><td colspan="2"><input type="submit" value="submit" /></colspan></td></tr>
</table>
</form>
</div>
FORM;
	
	print $return;

}

function build_cats ($name = "") {
	global $db;
	
	$get = mysql_query ("SELECT cat_name, cat_header FROM ".DB_PEREFIX."_art_category ORDER BY cat_id");
	$return = "";
	
	while (list($name_, $header) = mysql_fetch_row ($get)) {
		($name == $name_) ? $selected = "selected" : $selected = "";
		$return .= "\n<option value=\"$name_\" $selected>$header</option>";
	}
	
	return $return;
}

